// isUnauthorized returns:
//   true if the err means 'Unauthorized';
//   false if it is an error other than 'Unauthorized';
export function isUnauthorized(err) {
  if (!err) {
    return false
  }

  if (err?.response?.status === 401) {
    return true
  }

  if (err?.response?.errors) {
    for (let i = 0; i < err.response.errors.length; i++) {
      if (err.response.errors[i]?.extensions?.classification === 'UNAUTHORIZED') {
        return true
      }
    }
  }

  return false
}

// isForbidden returns:
//   true if the err means 'Forbidden';
//   false if it is an error other than 'Forbidden';
export function isForbidden(err) {
  if (!err) {
    return false
  }

  if (err?.response?.status === 403) {
    return true
  }

  if (err?.response?.errors) {
    for (let i = 0; i < err.response.errors.length; i++) {
      if (err.response.errors[i]?.extensions?.classification === 'FORBIDDEN') {
        return true
      }
    }
  }

  return false
}

// returns canonical error object: { code, message }
export function extractErrorObject(err) {
  // standard error object?
  if (err.reason && err.message) {
    return err;
  }

  // GraphQLError object?
  const errs = err?.response?.errors;
  if (errs && errs.length > 0) {
    let message = ''
    if (errs[0].message) {
      message = errs[0].message
    } else if (typeof errs[0] === 'string') {
      message = errs[0]
    }
    return {
      reason: errs[0]?.extensions?.classification,
      message: message,
    };
  }

  return err
}
